﻿using CAP.Core.IntegrationEvents;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CAP.Core.Api
{
    public class TestApi : ControllerBase
    {
        private readonly AppDbContext _context;
        private readonly ICapPublisher _capPublisher;

        public TestApi(AppDbContext context, ICapPublisher capPublisher)
        {
            _context = context;
            _capPublisher = capPublisher;
        }

        [HttpGet]
        [Route("test/index")]
        public string Index()
        {
            return "hello api";
        }


        [HttpPost]
        [Route("/adduser")]
        public async Task AddUser()
        {
            using (var transaction = await _context.Database.BeginTransactionAsync())
            {
                try
                {
                    _context.Add(new User() { Id = Guid.NewGuid().ToString(), UserName = "小强" });
                    await _context.SaveChangesAsync();
                    var r = new List<UserCreatedEvent>();
                    //for (int i = 0; i < 10000; i++)
                    //{
                    //    r.Add(new UserCreatedEvent
                    //    {
                    //    });
                    //}
                    await _capPublisher.PublishAsync("user.created", r);
                    // 提交事务
                    await transaction.CommitAsync();
                }
                catch (Exception)
                {
                    // 出现异常时回滚事务  
                    await transaction.RollbackAsync();
                    throw; // 可选择抛出或处理异常  
                }
            }
        }
    }

}
